/**
 * 
 */
package ro.dandanciu.webgallery.services.impl;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.Query;

import org.springframework.transaction.annotation.Transactional;

import ro.dandanciu.webgallery.domainmodel.Roles;
import ro.dandanciu.webgallery.domainmodel.User;
import ro.dandanciu.webgallery.services.UserServices;

/**
 * @author Dan
 * 
 */
@Transactional
public class UserServicesImpl extends AbstractServicesImpl implements UserServices {
	public void save(User user, String administrator) {
		user.setUpdater(administrator);
		em.persist(user);
	}

	
	public User getUserByUserId(String userId) {
		return em.find(User.class, userId);
	}
	
	
	public User getUserByUserIdAndPassword(String userId, String password) {
		User user = getUserByUserId(userId);
		
		if(user != null && password != null && password.equals(user.getPassword())) {
			return user;
		}
		
		return null;
	}

	
	public Set<Roles> getUserRoles(User user) {
		Set<Roles> roles = new TreeSet<Roles>();
		roles.add(Roles.PUBLIC);
		if(user != null) {
			roles.add(Roles.SIMPLE);
			if(user.isAdmin()) {
				roles.add(Roles.ADMIN);
			}
		}
		return roles;
	}

	@SuppressWarnings("unchecked")
	
	public List<User> getUsers(String filter) {
		Query query = em.createNamedQuery("User.GetAll");
		query.setParameter("filter", filter + "%");
		return (List<User>) query.getResultList();
	}

	public void save(String userId, User user, boolean ignorePassword, String updater) {
		User userFromDB = getUserByUserId(userId);
		userFromDB.setAdmin(user.isAdmin());
		userFromDB.setEmail(user.getEmail());
		userFromDB.setUserName(user.getUserName());
		if (!ignorePassword) {
			userFromDB.setPassword(user.getPassword());
		}
		userFromDB.setLanguage(user.getLanguage());
		userFromDB.setUpdater(updater);
		em.persist(userFromDB);
	}


	public void delete(String userId, boolean deleteOnFS) {
		User user = getUserByUserId(userId);
		if (user != null) {
			em.remove(user);
			if(deleteOnFS) {
				//TODO delete file-system structure
			}
		}
	}

}
